<!-- 查看题目 -->
<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="visible"
    width="1200px"
    append-to-body
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <!-- 搜索区域 -->
    <el-form
      :model="queryParams"
      inline
      size="small"
      label-width="80px"
      style="margin-bottom: 15px"
    >
      <el-form-item label="题目">
        <el-input
          v-model="queryParams.questionName"
          placeholder="请输入题目关键词"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          v-model="queryParams.rangeTime"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          clearable
          style="width: 240px"
        />
      </el-form-item>

      <el-form-item label="创建人">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人"
          clearable
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div style="margin-bottom: 15px; display: flex; gap: 10px">
      <el-button type="primary" plain @click="handleExport">导出</el-button>
      <el-button type="primary" plain @click="handleRelate">关联题目</el-button>
      <el-button type="primary" plain @click="handleCancelRelate"
        >取消关联</el-button
      >
    </div>

    <!-- 表格 -->
    <el-table
      :data="questionList"
      ref="table"
      @selection-change="handleSelectionChange"
      style="width: 100%"
      border
    >
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column
        label="题型"
        align="center"
        width="100"
        prop="questionType"
      >
        <template slot-scope="scope">
          <span>{{ dict.question_type[Number(scope.row.questionType)] }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="题目"
        align="center"
        min-width="300"
        prop="questionName"
      >
        <template slot-scope="scope">
          <span class="question-content" @click="showQuestionDetail(scope.row)">
            {{ scope.row.questionName }}
          </span>
        </template>
      </el-table-column>

      <el-table-column
        label="创建人"
        align="center"
        width="120"
        prop="createBy"
      />

      <el-table-column
        label="创建时间"
        align="center"
        width="180"
        prop="createTime"
      />

      <el-table-column label="操作" align="center" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleCancelRelateItem(scope.row)"
          >
            取消关联
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 题目详情弹窗 -->
    <el-dialog
      :title="detailTitle"
      :visible.sync="detailVisible"
      width="500px"
      append-to-body
    >
      <div v-html="questionDetailContent"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 关联题目弹窗 -->
    <RelateQuestionDialogVue
      :visible.sync="relateDialogVisible"
      :question-type="currentQuestionType"
      :question-group-id="questionGroupId"
      @confirm="handleConfirmRelate"
      :dict="dict"
    />

    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  getListInfo,
  getQuestion,
  viewQuestion,
} from "@/api/examination/question";
import { cancelAssociationQuestion } from "@/api/examination/questionGroup";
import RelateQuestionDialogVue from "./RelateQuestionDialog.vue";

export default {
  name: "ViewQuestionDialog",
  components: {
    RelateQuestionDialogVue,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    questionGroupId: {
      type: String,
      required: true,
    },
    dict: {
      type: Object,
      default: () => {},
    },
    //inex传过来的题型
    currentQuestionType: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      dialogTitle: "查看题目",
      detailTitle: "题目详情",
      detailVisible: false,
      questionDetailContent: "",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        questionName: "",
        rangeTime: [],
        createBy: "",
        questionGroupId: "", // 将由父组件传入
      },
      questionList: [],
      total: 0,
      selectedRows: [],
      relateDialogVisible: false,
    };
  },
  watch: {
    visible(val) {
      if (val) {
        this.getList();
      }
    },
    questionGroupId(newVal) {
      this.queryParams.questionGroupId = newVal;
    },
  },
  methods: {
    getList() {
      const params = { ...this.queryParams };
      params.questionType = this.currentQuestionType;
      params.relateGroupId = this.questionGroupId;
      viewQuestion(params).then((response) => {
        this.questionList = response.rows;
        this.total = response.total;
      });
    },
    handleClose() {
      this.resetAll();
      this.$emit("update:visible", false);
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        questionName: "",
        rangeTime: [],
        createBy: "",
        questionType: this.questionType, // 保持当前题型过滤条件
      };
      this.handleQuery();
    },

    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    handleRelate() {
      this.relateDialogVisible = true;
    },

    handleConfirmRelate(selectedQuestions) {
      console.log("已选择题目:", selectedQuestions);
      // 将新关联的题目添加到当前列表中
      const newQuestionIds = selectedQuestions.map((item) => item.questionId);
      this.$message.success("已成功关联题目");
      this.relateDialogVisible = false;
      this.getList(); // 刷新列表
    },

    handleCancelRelate() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请先选择要取消关联的题目");
        return;
      }

      this.$confirm(
        `确定要取消关联 ${this.selectedRows.length} 道题目吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          const questionIds = this.selectedRows.map((item) => item.questionId);
          const params = {
            groupId: this.questionGroupId,
            questionIds: questionIds,
          };
          cancelAssociationQuestion(params).then((response) => {
            this.$message.success("已成功取消关联");
            this.getList();
          });
        })
        .catch(() => {});
    },

    handleCancelRelateItem(row) {
      this.$confirm(`确定要取消关联题目 "${row.questionName}" 吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const params = {
            groupId: this.questionGroupId,
            questionIds: [row.questionId],
          };
          cancelAssociationQuestion(params).then((response) => {
            this.$message.success("已成功取消关联");
            this.getList();
          });
        })
        .catch(() => {});
    },

    showQuestionDetail(row) {
      // 模拟题目详情（实际应从后端获取）
      console.log("查看题目详情:", row);
      getQuestion(row.questionId).then((response) => {
        console.log("查看题目详情:", response);

        const questionData = response.data;
        // 构建题目详情HTML内容
        let optionsHtml = "";
        if (
          questionData.questionOptionList &&
          questionData.questionOptionList.length > 0
        ) {
          optionsHtml = questionData.questionOptionList
            .map(
              (option) =>
                `<li>${option.optionName}.${option.optionContent}</li>`
            )
            .join("");
        }

        this.questionDetailContent = `
      <p><strong>题目：</strong>${questionData.questionName}</p>
      <p><strong>选项：</strong></p>
      <ul>${optionsHtml}</ul>
      <p><strong>正确答案：</strong>${questionData.answer}</p>
      <p><strong>解析：</strong>${questionData.analysisContent || "无"}</p>
    `;
        this.detailVisible = true;
      });
    },
    handleExport() {
      this.$confirm("是否确认导出当前数据？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 调用导出接口
          this.download(
            "examination/question/export",
            { ...this.queryParams },
            `questions_${new Date().getTime()}.xlsx`
          );
        })
        .catch(() => {});
    },
    cancel() {
      this.resetAll();
      this.$emit("update:visible", false);
    },
    confirm() {
      this.$emit("confirm", this.selectedRows);
      this.cancel();
    },
    resetAll() {
      // 重置查询条件
      this.resetQuery();

      // 清空选择项
      this.selectedRows = [];

      // 清空表格选中状态
      if (this.$refs.table) {
        this.$refs.table.clearSelection();
      }

      // 重置题目详情相关状态
      this.detailVisible = false;
      this.questionDetailContent = "";

      // 关闭关联弹窗（如果打开）
      this.relateDialogVisible = false;
    },
  },
};
</script>